package br.ufrj.dcc.trabxml.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

import br.ufrj.dcc.trabxml.util.TrabUtil;

/**
 * 
 * @author Artur
 */
public class FormMain extends javax.swing.JFrame {
    
    private Collection<String> groups = null;
       
    private int myGroup = 0;

    /** Creates new form FormMain */
    public FormMain(int myGroup, Collection<String> groups) {
        this.groups = groups;
        this.setMyGroup(myGroup);
        initComponents();
        setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        pnBooks = new javax.swing.JPanel();
        pnSearchFields = new javax.swing.JPanel();
        cmbGroups = new javax.swing.JComboBox();
        txtSearchString = new javax.swing.JTextField();
        btnFindBook = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();
        itemNewBook = new javax.swing.JMenuItem();
        showHistory = new javax.swing.JMenuItem();

        getContentPane().setLayout(new java.awt.GridLayout(1, 1));

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Trabalho de XML 2007/2");
        jPanel2.setLayout(new java.awt.BorderLayout());

        jScrollPane1.setPreferredSize(new java.awt.Dimension(100, 100));
        pnBooks.setLayout(new java.awt.GridLayout(100, 1, 1, 1));

        pnBooks.setAutoscrolls(true);
        JPanel pnBooksContainer = new JPanel();
        pnBooksContainer.setLayout(new BorderLayout());
        pnBooksContainer.add(pnBooks,BorderLayout.NORTH);
        jScrollPane1.setViewportView(pnBooksContainer);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        pnSearchFields.setPreferredSize(new java.awt.Dimension(100, 48));
        
        Object[] arrayGroups = groups.toArray();
        for(int i = getMyGroup()-1; i > 0; i--) {
            arrayGroups[i] = arrayGroups[i-1];
        }
        arrayGroups[0] = "Local";
        
        cmbGroups.setModel(new javax.swing.DefaultComboBoxModel(arrayGroups));

        btnFindBook.setText("Buscar");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
                pnSearchFields);
        pnSearchFields.setLayout(jPanel1Layout);
        jPanel1Layout
                .setHorizontalGroup(jPanel1Layout
                        .createParallelGroup(
                                javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(
                                jPanel1Layout
                                        .createSequentialGroup()
                                        .addContainerGap()
                                        .addComponent(
                                                cmbGroups,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                113,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(
                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(
                                                txtSearchString,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                302, Short.MAX_VALUE)
                                        .addPreferredGap(
                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnFindBook)
                                        .addContainerGap()));
        jPanel1Layout
                .setVerticalGroup(jPanel1Layout
                        .createParallelGroup(
                                javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(
                                jPanel1Layout
                                        .createSequentialGroup()
                                        .addContainerGap()
                                        .addGroup(
                                                jPanel1Layout
                                                        .createParallelGroup(
                                                                javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(
                                                                cmbGroups,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addComponent(btnFindBook)
                                                        .addComponent(
                                                                txtSearchString,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addContainerGap(14, Short.MAX_VALUE)));
        jPanel2.add(pnSearchFields, java.awt.BorderLayout.NORTH);

        getContentPane().add(jPanel2);

        jMenu1.setText("Cadastro");

        itemNewBook.setText("Incluir Livro");
        jMenu1.add(itemNewBook);
        
        jMenu2.setText("Historico");
        showHistory.setText("Ver Historico");
        jMenu2.add(showHistory);

        jMenuBar1.add(jMenu1);
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        //pack();
        setSize(new java.awt.Dimension(640, 480));    
        
        ActionListener searchListener = new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (cmbGroups.getSelectedIndex() == 0) {
                    searchGroup = getMyGroup();
                } else {
                    searchGroup = Integer.parseInt(cmbGroups.getSelectedItem().toString());
                }
                findBookListener.actionPerformed(e);
            }
            
        };
        
        btnFindBook.addActionListener(searchListener);
        txtSearchString.addActionListener(searchListener);        
    }// </editor-fold>
    
    public void setSearchGroup(int searchGroup) { 
        this.searchGroup = searchGroup;
    }

    public int getSearchGroup() {
        return searchGroup;
    }

    private ActionListener findBookListener = null;
    
    private int searchGroup = getMyGroup();
    
    public void setFindBookListener(ActionListener listener) {
        findBookListener = listener;
    } 
    
    public void setNewBookListener(ActionListener listener) {
        itemNewBook.addActionListener(listener);
    }
    
    public void setShowHistoryListener(ActionListener listener) {
    	showHistory.addActionListener(listener);
    }
    
    public void setRemoveBookListener(ActionListener removeBookListener) {
        this.removeBookListener = removeBookListener;
    }

    public ActionListener getRemoveBookListener() {
        return removeBookListener;
    }

    private ActionListener removeBookListener = null;
    
    public void setDeleteISBN(String deleteISBN) {
        this.deleteISBN = deleteISBN;
    }

    public String getDeleteISBN() {
        return deleteISBN;
    }

    private String deleteISBN = null;
    
    public void setBooksNumber(int n) {
        pnBooks.removeAll();
        pnBooks.setLayout(new java.awt.GridLayout(n, 1, 1, 1));       
        pnBooks.repaint();
        pnBooks.revalidate();        
    }
    
    private ActionListener lendBookListener = null;
    
    public void setLendBookListener(ActionListener lendBookListener) {
        this.lendBookListener = lendBookListener;
    }

    public ActionListener getLendBookListener() {
        return lendBookListener;
    }
    
    private ActionListener returnBookListener = null;
    
    public void setReturnBookListener(ActionListener returnBookListener) {
        this.returnBookListener = returnBookListener;
    }

    public ActionListener getReturnBookListener() {
        return returnBookListener;
    }
    
    private int lendOwner;
    
    private String lendISBN;
    
    private String lendTitle;
    
    private String lendPublisher;
    
    private List<String> lendAuthors;
    
    private String lendObs;
    
    public String getSearchString() {
        return txtSearchString.getText();
    }
    
    public void focusSearch() {
        txtSearchString.requestFocus();
        txtSearchString.selectAll();
    }
    
    public void addBook(final String owner, final String isbn,final String title,final String publisher,final List<String> authors,final String obs, final int from, final int to) {
        JPanel pnBook = new JPanel();
        final JPanel pnBookWithImage = new JPanel();
        JLabel lblImage = null;
        JLabel lblTitle = new JLabel();
        JLabel lblISBNTxt = new JLabel();
        JLabel lblOwner = new JLabel();
        JLabel lblOwnerTxt = new JLabel();
        JLabel lblTitleTxt = new JLabel();
        JLabel lblAuthors = new JLabel();
        JLabel lblAuthorsTxt = new JLabel();
        JLabel lblPublisher = new JLabel();
        JLabel lblPublisherTxt = new JLabel();
        JLabel lblISBN = new JLabel();
        JButton btnInfo = new JButton();
        JButton btnRemove = new JButton();
        JButton btnCheckin = new JButton();
        JButton btnCheckout = new JButton();
        lblTitle.setText("T\u00edtulo:");
        lblTitleTxt.setText(title);
        lblAuthors.setText("Autor(es):");
        String authorsTxt = authors.get(0);
        for(int i = 1; i < authors.size(); i++) {
            authorsTxt += "; "+authors.get(i);
        }
        lblAuthorsTxt.setText(authorsTxt);
        lblPublisher.setText("Editora:");
        lblPublisherTxt.setText(publisher);
        lblISBN.setText("ISBN:");
        lblISBNTxt.setText(isbn);
        lblOwner.setText("Dono:");
        lblOwnerTxt.setText(owner);
        if ((from != myGroup) && (to != myGroup)) {
            lblOwnerTxt.setText(lblOwnerTxt.getText()+" (Emprestado do grupo "+from+"; Emprestado para o grupo "+to+")");
        }
        if ((from == myGroup) && (to != myGroup)) {
            lblOwnerTxt.setText(lblOwnerTxt.getText()+" (Emprestado para o grupo "+to+")");
        }  
        if ((from != myGroup) && (to == myGroup)) {
            lblOwnerTxt.setText(lblOwnerTxt.getText()+" (Emprestado do grupo "+from+")");
        }          
        btnInfo.setText("Info");
        btnRemove.setText("Excluir");
        btnCheckin.setText("Solicitar Empr\u00e9stimo");
        btnCheckout.setText("Devolver");
        javax.swing.GroupLayout pnBookLayout = new javax.swing.GroupLayout(pnBook);
        pnBook.setLayout(pnBookLayout);
        pnBookLayout.setHorizontalGroup(
            pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnBookLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblAuthors)
                    .addComponent(lblTitle)
                    .addComponent(lblPublisher)
                    .addComponent(lblISBN)
                    .addComponent(lblOwner)
                    .addComponent(btnInfo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnBookLayout.createSequentialGroup()
                        .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblOwnerTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                            .addComponent(lblISBNTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                            .addComponent(lblPublisherTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                            .addComponent(lblTitleTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                            .addComponent(lblAuthorsTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE))
                        .addGap(196, 196, 196))
                    .addGroup(pnBookLayout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addComponent(btnRemove)
                        .addGap(16, 16, 16)
                        .addComponent(btnCheckin)
                        .addGap(17, 17, 17)
                        .addComponent(btnCheckout)
                        .addContainerGap(1, Short.MAX_VALUE))))
        );
        pnBookLayout.setVerticalGroup(
            pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnBookLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblTitle)
                    .addComponent(lblTitleTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblAuthors)
                    .addComponent(lblAuthorsTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblPublisher)
                    .addComponent(lblPublisherTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblISBN)
                    .addComponent(lblISBNTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblOwner)
                    .addComponent(lblOwnerTxt))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnBookLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnInfo)
                    .addComponent(btnRemove)
                    .addComponent(btnCheckin)
                    .addComponent(btnCheckout))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        pnBookWithImage.setLayout(new BorderLayout());
        lblImage = new JLabel(new ImageIcon(TrabUtil.getBookImage(isbn)));
        lblImage.setVerticalAlignment(JLabel.TOP);
        lblImage.setBorder(BorderFactory.createEmptyBorder(3, 3, 0, 1));
        pnBookWithImage.add(lblImage,BorderLayout.WEST);
        pnBookWithImage.add(pnBook,BorderLayout.CENTER);
        if (searchGroup == myGroup) {
            btnCheckin.setEnabled(false);
            btnCheckout.setEnabled(false);
            if ((getMyGroup() != from) || (getMyGroup() != to)) {
                btnCheckout.setEnabled(true);
                btnRemove.setEnabled(false);
            }            
        } else {
            btnRemove.setEnabled(false);
            btnCheckin.setEnabled(false);
            btnCheckout.setEnabled(false);
            if ((myGroup == to) && (myGroup == from)) {
                if (!owner.equals(Integer.toString(myGroup))) {
                    btnCheckin.setEnabled(true);
                }
            } else {
                btnCheckout.setEnabled(true);
            }
        }     
        btnInfo.addActionListener(new ActionListener(){
        	public void actionPerformed(ActionEvent e){
        		FormObs myFormObs=new FormObs("Info sobre o livro "+isbn,obs);
        		myFormObs.setVisible(true);
        	}
        });
        btnRemove.addActionListener(new ActionListener() {
            
            private String delISBN = isbn;

            public void actionPerformed(ActionEvent e) {
                deleteISBN = delISBN;
                removeBookListener.actionPerformed(e);
                if (deleteISBN != null) {
                    return;
                }
                pnBooks.remove(pnBookWithImage);
                Component[] comps = pnBooks.getComponents();
                setBooksNumber(comps.length);
                for(int i = 0; i < comps.length; i++) {
                    pnBooks.add(comps[i]);
                }
            }
            
        });
        btnCheckin.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                lendISBN = isbn;
                lendOwner = Integer.parseInt(owner);
                lendTitle = title;
                lendPublisher = publisher;
                lendObs = obs;
                lendAuthors = authors;
                lendBookListener.actionPerformed(e);
            }
            
        });   
        
        btnCheckout.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                lendISBN = isbn;
                lendOwner = Integer.parseInt(owner);
                returnBookListener.actionPerformed(e);
                if ((lendISBN == null) && (searchGroup == myGroup)) {
                    pnBooks.remove(pnBookWithImage);
                    Component[] comps = pnBooks.getComponents();
                    setBooksNumber(comps.length);
                    for(int i = 0; i < comps.length; i++) {
                        pnBooks.add(comps[i]);
                    }
                }
                lendISBN = null;
            }
            
        });           
        pnBooks.add(pnBookWithImage);     
        pnBooks.repaint();
        pnBooks.revalidate();
    }

    public void setMyGroup(int myGroup) {
        this.myGroup = myGroup;
    }

    public int getMyGroup() {
        return myGroup;
    }

    public void setLendOwner(int lendOwner) {
        this.lendOwner = lendOwner;
    }

    public int getLendOwner() {
        return lendOwner;
    }

    public void setLendISBN(String lendISBN) {
        this.lendISBN = lendISBN;
    }

    public String getLendISBN() {
        return lendISBN;
    }

    // Variables declaration - do not modify
    private javax.swing.JMenuItem itemNewBook;
    
    private javax.swing.JMenuItem showHistory;

    private javax.swing.JButton btnFindBook;

    private javax.swing.JComboBox cmbGroups;

    private javax.swing.JMenu jMenu1;
    
    private javax.swing.JMenu jMenu2;

    private javax.swing.JMenuBar jMenuBar1;

    private javax.swing.JPanel pnSearchFields;

    private javax.swing.JPanel jPanel2;

    private javax.swing.JScrollPane jScrollPane1;

    private javax.swing.JTextField txtSearchString;

    private javax.swing.JPanel pnBooks;
    // End of variables declaration

    public String getLendTitle() {
        return lendTitle;
    }

    public void setLendTitle(String lendTitle) {
        this.lendTitle = lendTitle;
    }

    public String getLendPublisher() {
        return lendPublisher;
    }

    public void setLendPublisher(String lendPublisher) {
        this.lendPublisher = lendPublisher;
    }

    public List<String> getLendAuthors() {
        return lendAuthors;
    }

    public void setLendAuthors(List<String> lendAuthors) {
        this.lendAuthors = lendAuthors;
    }

    public String getLendObs() {
        return lendObs;
    }

    public void setLendObs(String lendObs) {
        this.lendObs = lendObs;
    }

}
